package com.fuhaiwei.basic.hibernate.impl;

import org.apache.log4j.Logger;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistryBuilder;

import com.fuhaiwei.basic.hibernate.HibernateSessionFactory;

public class HibernateSessionFactoryImpl implements HibernateSessionFactory {

	private final ThreadLocal<Session> tl = new ThreadLocal<Session>();
	private Configuration cfg = new Configuration();
	private SessionFactory sf;
	private ServiceRegistryBuilder srb;
	private String configurePath;

	public void closeSession() {
		Session session = (Session) tl.get();
		tl.set(null);

		if (session != null) {
			session.close();
		}
	}

	public Session getSession() {
		Session session = (Session) tl.get();

		if (session == null || !session.isOpen()) {
			if (sf == null) {
				rebuildSessionFactory();
			}
			session = (sf != null) ? sf.openSession() : null;
			tl.set(session);
		}

		return session;
	}

	public SessionFactory getSessionFactory() {
		return sf;
	}

	public void rebuildSessionFactory() {
		try {
			Logger logger = Logger.getLogger(this.getClass());
			if (configurePath == null) {
				logger.warn("hibernate.cfg.xml path not set, try default set!");
				configurePath = "hibernate.cfg.xml";
			}
			cfg = cfg.configure(configurePath);
			srb = new ServiceRegistryBuilder().applySettings(cfg
					.getProperties());
			sf = cfg.buildSessionFactory(srb.buildServiceRegistry());
		} catch (Exception e) {
			System.err.println("%%%% Error Creating SessionFactory %%%%");
			e.printStackTrace();
		}
	}

	public void setConfigurePath(String configurePath) {
		this.configurePath = configurePath;
		rebuildSessionFactory();
	}

}